﻿Public Class Core
    Inherits SingletonObject(Of Core)
    Const FieldName As String = "request"
    Const Version As String = "20210531"
    ReadOnly Property ServerAddress As String
        Get
#If DEBUG Then
            'Return TestLoginAddress
#End If
            Return LoginAddress
        End Get
    End Property
    ReadOnly Property ServerSession As String
        Get
#If DEBUG Then
            'Return "1d31e88e1d6e81c86c556abcd691aeb8"
#End If
            Return LoginSession
        End Get
    End Property
    Public Function PostData(Action As String, JsonObject As Sy.Data.JsonObject) As String
        Dim URL = $"{ServerAddress}{Action}?version={Version}&t={GetTimeStamp()}"
        Dim Json = If(JsonObject Is Nothing, "null", JsonObject.ToJson)
        Dim Data = $"{FieldName}={Sy.Text.Encode.Url_Encode(Json)}"
#If DEBUG Then
        'DebugLog?($"URL:{URL}")
        'DebugLog?($"Json:{Json}")
        'DebugLog?($"Post:{Data}")
#End If
        Return Sy.Net.Factory.Http(URL).SetData(Json).SetCookies($"erp_session={ServerSession};").Post()
    End Function
    Public Function Invoke(Api As IApi, JsonObject As Sy.Data.JsonObject, Log As LogSub) As TryResult
        Dim JsonPage = PostData(Api.Action, JsonObject)
        'Threading.Thread.Sleep(10000)
        Dim Res = Response.Analysis(JsonPage)
        If JsonPage.Length > 0 Then
            Dim State As StateCode
            If Res.Code.Equals(StateCode.Analysis) Then
                Log($"服务器出现异常:[{Api.Action}]")
            Else
                If [Enum].IsDefined(GetType(StateCode), Res.Code) AndAlso [Enum].TryParse(Res.Code, State) Then
                    Select Case State
                        Case StateCode.Success
                            Return Api.DealSuccess(Res.Code, Res.Data, Log)
                        Case Else
                            Return Api.DealFail(State, Res.Data, Log)
                    End Select
                Else
                    Return Api.Deal(Res.Code, Res.Data, Log)
                End If
            End If
        Else
            Log("网络或服务器出现异常")
        End If
        Return TryResult.ReTry
    End Function
End Class
